package one;
//命令模式

//接收者类
class Light {
 public void turnOn() {
     System.out.println("Light is on");
 }

 public void turnOff() {
     System.out.println("Light is off");
 }
}

//命令接口
interface Command {
 void execute();
}

//具体命令类 TurnOnCommand
class TurnOnCommand implements Command {
 private Light light;

 public TurnOnCommand(Light light) {
     this.light = light;
 }

 @Override
 public void execute() {
     light.turnOn();
 }
}

//具体命令类 TurnOffCommand
class TurnOffCommand implements Command {
 private Light light;

 public TurnOffCommand(Light light) {
     this.light = light;
 }

 @Override
 public void execute() {
     light.turnOff();
 }
}

//调用者类
class RemoteControl {
 private Command command;

 public void setCommand(Command command) {
     this.command = command;
 }

 public void pressButton() {
     command.execute();
 }
}

//测试命令模式
public class CommandPatternDemo {
 public static void main(String[] args) {
     Light light = new Light();
     Command turnOn = new TurnOnCommand(light);
     Command turnOff = new TurnOffCommand(light);

     RemoteControl remote = new RemoteControl();

     remote.setCommand(turnOn);
     remote.pressButton(); // 输出 "Light is on"

     remote.setCommand(turnOff);
     remote.pressButton(); // 输出 "Light is off"
 }
}



